package frontend.pages.admin.activity;

import backend.service.admin.ActivityService;
import frontend.components.base.ComponentFactory;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.ActivityUIModel;
import frontend.pages.admin.base.AbstractManagingForm;
import org.apache.wicket.markup.html.panel.Panel;

public class ActivityForm extends AbstractManagingForm<ActivityUIModel> {

    private static final String RESOURCE_KEY_FIELD_LABEL_NAME = "pages.admin.activity.form.name";
    private static final String RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE = "pages.admin.activity.form.isActive";

    private static final String RESOURCE_KEY_VALIDATION_SAME_PROJECT_NAME = "validation.form.activity.sameActivityName";

	public ActivityForm(String id, ActivityUIModel activityUIModel) {
		super(id, activityUIModel);		
	}

	@Override
	protected void constructFormContent() {
        Panel nameComponent = ComponentFactory.createTextFieldComponent("name", RESOURCE_KEY_FIELD_LABEL_NAME, uiModel);
        Panel isActiveComponent = ComponentFactory.createCheckboxComponent("isActive", RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE, uiModel);

		add(nameComponent, isActiveComponent);
	}

    @Override
    protected Class getResponsePage() {
        return ActivityManagingPage.class;
    }

    @Override
    protected void doFormValidation() {
        validateNotEmpty(uiModel.getName(), RESOURCE_KEY_FIELD_LABEL_NAME);
        if ((uiModel.getName() != null) && nameWasChanged()) {
            ActivityService service =  TimeTrackingWebApplication.getService(ActivityService.class);
            if (service.findActivityByName(uiModel.getName()) != null) {
                addFieldValidationError(RESOURCE_KEY_FIELD_LABEL_NAME, RESOURCE_KEY_VALIDATION_SAME_PROJECT_NAME);
            }
        }
    }

    private boolean nameWasChanged() {
        return (false == uiModel.getName().equals(uiModel.getDBModel().getName()));
    }
}
